package controllers;

import helpers.CrawlerAppShopperHelper;
import helpers.DateHelper;
import helpers.StringHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import services.Blogger;
import data.AutoSiteData;
import data.BlogData;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheManager;

import models.AppShopper;
import models.AutoSite;
import models.Blog;
import models.News;

public class CreateDailyPriceDrop extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		response.setContentType("text/html");
		ArrayList<AppShopper> iphoneApps = new ArrayList<AppShopper>();
		ArrayList<AppShopper> ipadApps = new ArrayList<AppShopper>();
		
		String today = DateHelper.getStringFromDate((Date) new Date(), "EEEE MMM d, yyyy");
		
		//Set cache
        Cache cache=null;
        String cachenameIphone = "dailyapp_iphone";
        String cachenameIpad = "dailyapp_ipad";
        String cachename = today;
        try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           e.printStackTrace();
        }
        
        /*if (cache.containsKey(cachenameIphone)) {
        	iphoneApps = (ArrayList<AppShopper>) cache.get(cachenameIphone);
        	System.out.println("AppShopper: iphone cache print");
        } else {
        	iphoneApps = CrawlerAppShopperHelper.getApp("http://appshopper.com/iphone/prices/");
        	if (iphoneApps.size() > 0) {
        		cache.put(cachenameIphone, iphoneApps);
        	}
	        System.out.println("AppShopper: iphone data print");
        }
        
        if (cache.containsKey(cachenameIpad)) {
        	ipadApps = (ArrayList<AppShopper>) cache.get(cachenameIpad);
        	System.out.println("AppShopper: ipad cache print");
        } else {
        	ipadApps = CrawlerAppShopperHelper.getApp("http://appshopper.com/ipad/prices/");
        	if (iphoneApps.size() > 0) {
        		cache.put(cachenameIpad, ipadApps);
        	}
	        System.out.println("AppShopper: ipad data print");
        }*/
        iphoneApps = CrawlerAppShopperHelper.getApp("http://appshopper.com/iphone/prices/");
        ipadApps = CrawlerAppShopperHelper.getApp("http://appshopper.com/ipad/prices/");
        
        String title = "Today's App Price Drop: ";
		String nameApp = "";
		for (int i = 0; i < iphoneApps.size(); i++) {
			nameApp += iphoneApps.get(i).getName() + ", ";
			if (i >=5)
				break;
		}
        title += nameApp + " and more apps.";
		
		String description = "<p style=\"overflow: hidden;\">Today, " + today + " has many apps price drop as: " + nameApp + " and more apps. List app price be provided below. News of the price drop apps we provide daily.</p>";
		description += "<p style=\"overflow: hidden;\"><strong>All app prices  will be retrieved from itunes, app price change at any time and without notice. This price only app for the present time in this post.</strong></p>";
		description += "<h2>Iphone: </h2>";
		description += getListAppText(iphoneApps);
		
		description += "<h2>Ipad: </h2>";
		description += getListAppText(ipadApps);
		
		//Insert into blogger
		/*if (!cache.containsKey(cachename)) {
			cache.put(cachename, today);
			
		}*/
		
		News news = new News();
		news.setLabels(Arrays.asList("price drop"));
		news.setTitle(title);
		news.setDescription(description);
		news.setPublished(true);
		news.setUrl("http://www.1streview.org/");
		//Post news to blogger
		ArrayList<AutoSite> sites = AutoSiteData.getAlls();
		AutoSite site = new AutoSite();
		String blogId = "";
		for (int i = 0; i < sites.size(); i++) {
			site = sites.get(i);
			blogId = site.getBlogId();
			break;
		}
		if (!blogId.isEmpty()) {
			Blog blog = BlogData.getById(blogId);
			Blogger blogger = new Blogger(blog);
			try {
				blogger.createPost(news);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		response.getWriter().println(title);
		response.getWriter().println(description);
	}
	
	private String getListAppText(ArrayList<AppShopper> apps) {
		String description = "";
		for (int i = 0; i < apps.size(); i++) {
			String txtApp = "<p style=\"overflow: hidden;\">";
			txtApp += "<a href=\"http://www.1stapp.org/i/"+ StringHelper.replace(apps.get(i).getName()) + "-" + apps.get(i).getId() + "\">";
			txtApp += "<img height=\"57\" width=\"57\" alt=\"\" src=\"" + apps.get(i).getImage() + "\" style=\"float: left; margin: 0px 5px 3px 0px; overflow: hidden;\">";
			txtApp += "</a>";
			txtApp += "<a href=\"http://www.1stapp.org/i/"+ StringHelper.replace(apps.get(i).getName()) + "-" + apps.get(i).getId() + "\"><em>" + apps.get(i).getName() + "</em></a>";
			txtApp += " (<strong style=\"color: #FFFFFF\">" + apps.get(i).getPriceDrop() + " -> " + apps.get(i).getPrice() + " </strong>, Version: " + apps.get(i).getVersion() + "): " + apps.get(i).getDescription();
			txtApp += "</p>";
			description += txtApp;
		}
		return description;
	}
}
